//
//  ZZComposeViewController.swift
//  web
//
//  Created by 张卓 on 2017/2/8.
//  Copyright © 2017年 ZZ. All rights reserved.
//

import UIKit

class ZZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   //MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = ZZRandomColor()
        
        setupNav()
        
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        view.addSubview(composePictureView)
        //设置约束
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        composeBottomView.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        composePictureView.snp_makeConstraints { (make) in
            make.size.equalTo(CGSize(width: ZZSCREENW - 20, height: ZZSCREENW - 20))
            make.top.equalTo(composeTextView).offset(164)
            make.centerX.equalTo(composeTextView)
        }
        //2. 闭包实例化
        composeBottomView.closure = {[weak self](type)->() in
            //4. 回调
            switch type {
            case .picture:
                print("图片")
                self?.selectImg()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                //切换键盘
                self?.switchKeyboard()
            case .add:
                print("+")
            }
        }
        //2. 监听配图中加好按钮点击
        composePictureView.closure = {[weak self]()->() in
            //4.  回调
            self?.selectImg()
        }
        //监听键盘将要弹出
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoard), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //监听表情键盘的表情按钮点击
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonNoti), name: NSNotification.Name(rawValue: EMOTICONBUTTONNOTI), object: nil)
        //监听表情键盘的表情按钮的删除
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonDeleteButtonNoti), name: NSNotification.Name(rawValue: EMOTICONDELETEBUTTONNOTI), object: nil)
        
    }
    
    
    
    
    private func setupNav(){                              
        //左右按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: nil, title: "发送", target: self, action: #selector(sendAction))
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: nil, title: "取消", target: self, action: #selector(cancelAction))
        self.navigationItem.rightBarButtonItem?.isEnabled = false
        navigationItem.titleView = titleView
    }
    //底部视图
    fileprivate lazy var composeBottomView : ZZComposeBottomView = ZZComposeBottomView()
    
    //MARK: - 懒加载控件
    private lazy var titleView : UILabel = {
        //获取当前用户昵称
        let name = ZZOAuthViewModel.shared.userAccountModel?.screen_name ?? ""
        //设置发布微博最终显示内容
        let str = "发微博\n\(name)"
        //获取范围 -> OC
        let rang = (str as NSString).range(of: name)
        //可变 副文本
        let attr = NSMutableAttributedString(string: str)
        //设置富文本的属性,字体的颜色和大小
        attr.addAttributes([NSForegroundColorAttributeName: ZZThemeColor, NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: rang)
        let lab = UILabel()
        //设置text
        lab.attributedText = attr
        //换行
        lab.numberOfLines = 0
        //对齐方式
        lab.textAlignment = .center

        //设置大小
        lab.sizeToFit()
        return lab
    }()
    //自定义textView
    fileprivate lazy var composeTextView : ZZComposeTextView = {
        let view = ZZComposeTextView()
        view.placeholder = "what the fuck day"
        view.font = UIFont.systemFont(ofSize: ZZNORMALFONTSIZE)
        view.delegate = self
        //允许 textView 垂直滚动
        view.alwaysBounceVertical = true
        return view
    }()
    
    //配图
    fileprivate lazy var composePictureView: ZZComposePictureView = ZZComposePictureView()
    
    //键盘表情
    fileprivate lazy var emoticonKeyboardView: ZZEmotionKeyboardView = ZZEmotionKeyboardView()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK : - 监听ZZComposeBottomView 中按钮的事件
extension ZZComposeViewController {
    //从相册获取图片
    func selectImg(){
        //实例化
        let pickerVC = UIImagePickerController()
        //设置代理
        pickerVC.delegate = self
        //打开相册
        self.present(pickerVC, animated: true, completion: nil)
    }
    //切换键盘
    func switchKeyboard(){
        
        //如果inputView == nil 就代表系统键盘  改成自定义键盘
        if self.composeTextView.inputView == nil {
            self.composeTextView.inputView = self.emoticonKeyboardView
            
            self.composeBottomView.isEmoticon = true
        }else{
            self.composeTextView.inputView = nil
            
            self.composeBottomView.isEmoticon = false
        }
        //如果不等于nil 就代表自定义键盘  改成系统键盘
        
        //开启第一响应
        self.composeTextView.becomeFirstResponder()
        //刷新
        self.composeTextView.reloadInputViews()
        
    }
}
//MARK: - UIImagePickerControllerDelegate
extension ZZComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取image
        let img = info[UIImagePickerControllerOriginalImage] as! UIImage
//        self.composeTextView.backgroundColor = UIColor(patternImage: img)
        
        
//        let data = (UIImagePNGRepresentation(img.dealImgScale(width: 400)) as? NSData)
       
        //把Image 传给 picView
        self.composePictureView.addImg(image: img.dealImgScale(width: 400))
        
        //关闭控制器
        picker.dismiss(animated: true, completion: nil)
    }
  
    
}
//监听通知
extension ZZComposeViewController {
    //监听键盘的frame将要发生改变
    func keyBoard(noti: Notification){
        //判断userINfo是否为nil 是否可以转换成字典
        guard let userInfo = noti.userInfo as? [String: Any] else {
            return
        }
        //获取键盘动画时间
        let time = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //获取键盘的frame
        let keyFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        //更改底部视图的bottom
        
        self.composeBottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyFrame.origin.y - ZZSCREENH)
        }
        //设置动画
        UIView.animate(withDuration: time) {
            //刷新
            self.view.layoutIfNeeded()
        }
    }
    //监听表情按钮的点击 
    func emoticonButtonNoti(noti: Notification){
        //判断是否为nil 且是否可以转换成ZZEMOdel
        guard let emoticonModel = noti.object as? ZZEmoticonModel else {
            return
        }
        // 1 保存用户点击的那个表情模型
        ZZEmoticonTools.shared.saveRecentModel(emoticonModel: emoticonModel)
        // 刷新pageView
        self.emoticonKeyboardView.reloadRecentData()
        
        // 判断如果是emoji表情
        if emoticonModel.isEmoji {
            let code = ((emoticonModel.code ?? "") as NSString).emoji()
            self.composeTextView.insertText(code!)
        }else{
            // 获取当前composeTextView上的富文本
            let allAttr  = NSMutableAttributedString(attributedString: self.composeTextView.attributedText)
            //图片表情

             let attr = NSAttributedString.emoticonAttributedString(emoticonModel: emoticonModel)
            // 获取当前ComposeText 的selectRang(光标)
            let selectRange = self.composeTextView.selectedRange
            //替换
            allAttr.replaceCharacters(in: selectRange, with: attr)
            // 范围
            let rang = NSRange(location: 0, length: allAttr.length)
            //设置字体大小
            allAttr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: ZZNORMALFONTSIZE)], range: rang)
            //设置富文本给textView
            self.composeTextView.attributedText = allAttr
            //重新设置他的光标位置
            self.composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            // 要把conposeTextView占位文字隐藏
            // 帮系统发布通知
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            //要把导航拦右侧的按钮修改状态
            // 使用代理调用协议方法
            self.composeTextView.delegate?.textViewDidChange!(self.composeTextView)
        }
        
    }
    
    //监听删除按钮的点击
    func emoticonDeleteButtonNoti() {
        //删除
        self.composeTextView.deleteBackward()
    }
}



extension ZZComposeViewController : UITextViewDelegate {
    
    //文字发生改变
    func textViewDidChange(_ textView: UITextView) {
        //使右侧按钮不能点击
        self.navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //取消第一响应
        self.composeTextView.resignFirstResponder()
    }
    
    
}
extension ZZComposeViewController{
    @objc fileprivate func sendAction(){
        print("发送")
        //A 图片 -> A[马到成功]a
        
        let rang = NSRange(location: 0, length: composeTextView.attributedText.length)
        //定义一个字符串进行拼接
        var allText = ""
        // 枚举遍历
        composeTextView.attributedText.enumerateAttributes(in: rang, options: []) { (info, rang, _) in
            // 文件附本
            if let att = info["NSAttachment"] as? ZZTextAttachment {
                allText += (att.emoticonModel?.chs ?? "")
            }else {
                //普通字符串
                allText += composeTextView.attributedText.attributedSubstring(from: rang).string
            }
        }
        
        
        if self.composePictureView.images.count > 0 {
            //图片微博
            upload(status: allText)
        }else{
            upDate(status: allText)
        }
    }
    
    @objc fileprivate func cancelAction(){
        dismiss(animated: true, completion: nil)
    }
    
}


//MARK: - 发布微博
extension ZZComposeViewController {
    //发布文字微博
    func upDate(status: String){
        HMNetworkTools.shared.upDate(status: status, success: { (res) in
            print("成功")
        }) { (error) in
            print("失败")
        }
    }
    
    func upload(status: String){
        
        HMNetworkTools.shared.upload(status: status, images: self.composePictureView.images, success: { (res) in
            print("发送成功")
        }) { (error) in
            print("发送失败",error)
        }
        
    }
    
}












